package com.isoft.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateDeserializer extends StdDeserializer<Date> {

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText(); // 获取文本内容
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null; // 如果为空或仅包含空白字符，则返回null
        }
        try {
            return formatter.parse(dateStr);
        } catch (Exception e) {
            throw ctxt.weirdStringException(dateStr, Date.class, "Failed to parse date: " + dateStr);
        }
    }
}
